<template>
  <p v-if="loading"/>
  <el-skeleton :rows="20" animated v-if="loading"/>
  <div v-for="(value_root, key) of res" :key="key">
    <el-card shadow="always">
      <template #header>
        <div class="card-head">
          <h3>{{ key }}</h3>
          <p v-if="value_root['tag']!==''">{{ value_root['tag'] }}</p>
        </div>
      </template>
      <el-checkbox-group v-model="checkboxGroups[key]" size="large" @change="saveData">
        <el-space wrap style="display:flex;justify-content:center;">
          <template v-for="(status, code) of value_root['status']" :key="status">
            <el-checkbox style="width:100px" v-if="status!=='借出'" :label="formatter(code)+'号'" border/>
            <el-checkbox style="width:100px" v-else disabled :checked="true" :label="formatter(code)+'号'" border/>
          </template>
        </el-space>
      </el-checkbox-group>
    </el-card>
    <p/>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "DeviceForm",
  props: ['category', 'place'],
  data() {
    return {
      res: null,
      loading: true,
      checkboxGroups: {},
    }
  },
  methods: {
    formatter: function (code) {
      return code < 10 ? '0' + code : code.toString()
    },
    saveData: function () {
      let temp = {}
      let preData = window.localStorage[this.place] ? JSON.parse(window.localStorage[this.place]) : {}
      temp[this.category] = this.checkboxGroups
      let nowData = Object.assign(preData, temp)
      window.localStorage[this.place] = JSON.stringify(nowData)
      window.localStorage.time = (new Date()).valueOf();
    }
  },
  created() {
    axios.get('/api/getByCategory', {
      params: {
        "category": this.category,
        "permission": 1,
        'place': this.place
      }
    }).then((response) => {
      this.res = response.data
      try {
        this.checkboxGroups = JSON.parse(window.localStorage[this.place])[this.category]
        if(!this.checkboxGroups) {
          this.checkboxGroups = {}
          for (let key in response.data) {
            this.checkboxGroups[key] = []
          }
        }
      } catch (e) {
        this.checkboxGroups = {}
        for (let key in response.data) {
          this.checkboxGroups[key] = []
        }
      }
      setTimeout(() => {
        this.loading = false
      }, 500);
    })
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.items {
  text-align: left;
}

p {
  color: #c0c4cc;
}
</style>